# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2005-2006 CamptoCamp
# Copyright (c) 2006-2010 OpenERP S.A
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly advised to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import time, os
from openerp.osv import osv, fields
from openerp.tools.translate import _
from openerp.report import report_sxw
import locale
locale.setlocale(locale.LC_ALL, '')

class timesheet_report(report_sxw.rml_parse):
    _name = 'timesheet.report'

    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        #Out Default Value
        data_header = ''
        data_ids = []
        #Declaration

        if context is None:
            context = {}
        
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike', input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
                
        return data_header, data_ids
    
    def set_context(self, objects, data, ids, context=None):
        new_ids = ids
        
        user_obj = self.pool.get('res.users')
        if context is None:
            context = {}
            
        self.department_selection = data['form']['department_selection'] or False
        self.department_name_ids = data['form']['department_name_ids'] or False
        self.sortby_ids = data['form']['sortby_ids'] or False
        self.output_project_header, self.project_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('project.project'),
                                                                                      [('state','!=','cancelled')],
                                                                                      data['form']['filter_selection'],
                                                                                      data['form']['project_default_from'] and data['form']['project_default_from'][0] or False,
                                                                                      data['form']['project_default_to'] and data['form']['project_default_to'][0] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)

        self.output_task_header, self.task_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('project.task'),
                                                                                      [],
                                                                                      data['form']['task_selection'],
                                                                                      data['form']['project_task_default_from'] and data['form']['project_task_default_from'][0] or False,
                                                                                      data['form']['project_task_default_to'] and data['form']['project_task_default_to'][0] or False,
                                                                                      data['form']['project_task_input_from'] or False,
                                                                                      data['form']['project_task_input_to'] or False,
                                                                                      data['form']['project_task_name_ids'] or False,
                                                                                      context=context)
        
        self.output_emp_header, self.emp_ids = self._search_data(self.cr, self.uid, ids, self.pool.get('hr.employee'),
                                                                                      [],
                                                                                      data['form']['employee_selection'],
                                                                                      data['form']['employee_default_from'] and data['form']['employee_default_from'][0] or False,
                                                                                      data['form']['employee_default_to'] and data['form']['employee_default_to'][0] or False,
                                                                                      data['form']['employee_input_from'] or False,
                                                                                      data['form']['employee_input_to'] or False,
                                                                                      data['form']['employee_name_ids'] or False,
                                                                                      context=context)
        
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        
        output_date_header = ''
        val_date = []
        if data['form']['date_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date','>=',str(date_from)))
                val_date.append(('date','<=',str(date_to)))

        self.output_date_header = output_date_header
        self.val_date = val_date
        
        output_dept_header = dept_str = dept_name = ''
        val_dept = []
        if data['form']['department_selection'] != 'all_vall':
            department_ids = self.pool.get('param.time.sheet.report.dept').search(self.cr, self.uid, [('id', 'in', data['form']['department_name_ids'])])
            for dept in self.pool.get('param.time.sheet.report.dept').browse(self.cr, self.uid, department_ids):
                val_dept.append((dept['name']))
 
            for rs in val_dept:
                if rs == 'shipyard':
                    dept_name = 'Shipyard'
                elif rs == 'mechanical':
                    dept_name = 'Mechanical'
                elif rs == 'electrical':
                    dept_name = 'Electrical'
                elif rs == 'welding_fabrication':
                    dept_name = 'Welding & Fabrication'
                elif rs == 'interior':
                    dept_name = 'Interior'
                elif rs == 'design':
                    dept_name = 'Design'
                elif rs == 'other_dept1':
                    dept_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept1_alias or 'Department1'
                elif rs == 'other_dept2':
                    dept_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept2_alias or 'Department2'
                elif rs == 'other_dept3':
                    dept_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept3_alias or 'Department3'
                
                dept_str += ('"%s",')%(dept_name,)
            output_dept_header = dept_str
        
        self.val_dept = val_dept
        self.output_dept_header = output_dept_header
        
        output_billing_header = ''
        val_billing = []
        if data['form']['billing_type'] == 'bill':
            val_billing.append(('task_id.project_id.analytic_account_id.billing_type','=','bill'))
            output_billing_header = "Actual"
        elif data['form']['billing_type'] == 'unbill':
            val_billing.append(('task_id.project_id.analytic_account_id.billing_type','=','unbill'))
            output_billing_header = "Non Actual"

        self.output_billing_header = output_billing_header
        self.val_billing = val_billing
        
        return super(timesheet_report, self).set_context(objects, data, new_ids)

    def __init__(self, cr, uid, name, context=None):
        super(timesheet_report, self).__init__(cr, uid, name, context=context)
        self.localcontext.update({
            'time': time,
            'locale': locale,
            'get_printed_date' : self._get_printed_date,
            'get_printed_by': self._get_printed_by,
            'get_output_project_header': self._get_output_project_header,
            'get_output_task_header': self._get_output_task_header,
            'get_output_emp_header': self._get_output_emp_header,
            'get_output_dept_header': self._get_output_dept_header,
            'get_output_date_header': self._get_output_date_header,
            'get_output_billing_header': self._get_output_billing_header,
            'get_output_sortby_header': self._get_output_sortby_header,
            'get_lines': self._get_lines,
            })
    
    def _get_printed_date(self):
        header = ''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            tz = user_obj.browse(self.cr, self.uid, user_ids[0])
            tz_name = tz.tz
        os.environ['TZ'] = tz_name
        time.tzset()
        header = 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S")
         
        return header
    
    def _get_printed_by(self):
        header =''
        user_obj = self.pool.get('res.users')
        user_ids = user_obj.search(self.cr, self.uid, [('id','=',self.uid)])
        if user_ids :
            user_id = user_obj.browse(self.cr, self.uid, user_ids[0])
            user_name = user_id.name
        
        header = 'Printed by : ' + user_name
        
        return header
    
    def _get_output_project_header(self):
        header = ''
        if self.output_project_header:
            header = 'Project : ' + self.output_project_header
         
        return header
    
    def _get_output_task_header(self):
        header = ''
        if self.output_task_header:
            header = 'Task : ' + self.output_task_header
         
        return header
    
    def _get_output_emp_header(self):
        header = ''
        if self.output_emp_header:
            header = 'Employee : ' + self.output_emp_header
         
        return header
    
    def _get_output_dept_header(self):
        header = ''
        if self.output_dept_header:
            header = 'Department : [' + self.output_dept_header + ']'
            
        return header
    
    def _get_output_date_header(self):
        header = ''
        if self.output_date_header:
            header = self.output_date_header
         
        return header
    
    def _get_output_billing_header(self):
        header = ''
        if self.output_billing_header:
            header = 'Billing : "' + self.output_billing_header + '"'
         
        return header
    
    def _get_output_sortby_header(self):
        header = output_sortby_header = ''
        result = []
        
        if self.sortby_ids:
            timesheet_sortby_ids = self.pool.get('timesheet.sortby').search(self.cr, self.uid, [('id', 'in', self.sortby_ids)], order='seq desc')
        
        if timesheet_sortby_ids:
            for item in self.pool.get('timesheet.sortby').browse(self.cr, self.uid, timesheet_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'task_name':
                    sort_name = 'Task'
                elif rs['sort_by'] == 'date_ptw':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'emp_name':
                    sort_name = 'Employee'
                elif rs['sort_by'] == 'dept':
                    sort_name = 'Department'
                elif rs['sort_by'] == 'billing':
                    sort_name = 'Billing'
                output_sortby_header += ('"%s",')%(sort_name,)
            header = 'Sort By : ' + output_sortby_header

        return header
    
    def _get_lines(self):
        cr  = self.cr
        uid = self.uid
        
        user_obj = self.pool.get('res.users')
        project_task_work_obj = self.pool.get('project.task.work')
        timesheet_sortby_obj = self.pool.get('timesheet.sortby')
        emp_obj = self.pool.get('hr.employee')

        results       = []
        val_task_work = []
         
        project_ids = self.project_ids
        task_ids = self.task_ids
        emp_ids = self.emp_ids
        bill_name = department_name = ''
        output_sortby_header = ''
        
        if project_ids:
            val_task_work.append(('task_id.project_id','in',project_ids))
        if task_ids:
            val_task_work.append(('task_id','in',task_ids))
        user_ids = []
        if emp_ids:
            for emp_id in emp_obj.browse(cr, uid, emp_ids):
                if emp_id.user_id:
                    user_ids.append(emp_id.user_id.id)
            val_task_work.append(('user_id','in',user_ids))
        if self.val_date:
            val_task_work += self.val_date
        if self.val_dept:
            val_task_work.append(('department','in',self.val_dept))
        if self.val_billing:
            val_task_work += self.val_billing
        
        timesheet_sortby_ids = []
        if self.sortby_ids:
            timesheet_sortby_ids = timesheet_sortby_obj.search(cr, uid, [('id', 'in', self.sortby_ids)], order='seq desc')
            
        project_task_work_ids = project_task_work_obj.search(cr, uid, val_task_work)
        if project_task_work_ids:
            ptw_ids = []
            
            for ptw in project_task_work_obj.browse(cr, uid, project_task_work_ids):
                emp_id = emp_obj.search(cr, uid, [('user_id', '=', ptw.user_id.id)])
                emp_name = (emp_id and emp_obj.browse(cr, uid, emp_id[0]).name) or ''
                emp_no = (emp_id and emp_obj.browse(cr, uid, emp_id[0]).employee_no) or ''
                ptw_ids.append({
                    'project_name' : ptw.task_id.project_id.name,
                    'task_name' : ptw.task_id.name,
                    'date_ptw' : ptw.date,
                    'emp_name' : emp_name,
                    'dept' : ptw.department,
                    'emp_no' : emp_no,
                    'type' : ptw.type,
                    'ptw_hours' : ptw.hours,
                    'billing' : ptw.task_id.project_id.analytic_account_id.billing_type,
                })
            if timesheet_sortby_ids:
                for timesheet_sortby in timesheet_sortby_obj.browse(cr, uid, timesheet_sortby_ids):
                    ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res[timesheet_sortby.sort_by]) or []               
            else:
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['billing']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['dept']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['emp_name']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['date_ptw']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['task_name']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['project_name']) or []
            
            for ptw_result in ptw_ids:
                if ptw_result['dept'] == 'shipyard':
                    department_name = 'Shipyard'
                elif ptw_result['dept'] == 'mechanical':
                    department_name = 'Mechanical'
                elif ptw_result['dept'] == 'electrical':
                    department_name = 'Electrical'
                elif ptw_result['dept'] == 'welding_fabrication':
                    department_name = 'Welding & Fabrication'
                elif ptw_result['dept'] == 'interior':
                    department_name = 'Interior'
                elif ptw_result['dept'] == 'design':
                    department_name = 'Design'
                elif ptw_result['dept'] == 'other_dept1':
                    department_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept1_alias or 'Department1'
                elif ptw_result['dept'] == 'other_dept2':
                    department_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept2_alias or 'Department2'
                elif ptw_result['dept'] == 'other_dept3':
                    department_name = user_obj.browse(self.cr, self.uid, self.uid).company_id.dept3_alias or 'Department3'
                
                if ptw_result['billing'] == 'bill':
                    bill_name = 'Actual'
                elif ptw_result['billing'] == 'unbill':
                    bill_name = 'Non Actual'
                
                results.append({
                    'project_name' : ptw_result['project_name'],
                    'task_name' : ptw_result['task_name'],
                    'date_ptw' : ptw_result['date_ptw'],
                    'emp_name' : ptw_result['emp_name'],
                    'dept' : department_name,
                    'emp_no' : ptw_result['emp_no'],
                    'type' : ptw_result['type'],
                    'ptw_hours' : ptw_result['ptw_hours'],
                    'billing' : bill_name,
                })

        return results
        
report_sxw.report_sxw('report.timesheet.report_landscape', 'param.time.sheet.report',
    'addons/batam_fast_module/project/report/report/timesheet_report.rml', parser=timesheet_report, header=False)
